'use strict';
const db = uniCloud.database();
const $ = db.command.aggregate
const cmd = db.command
exports.main = async (event, context) => {
	const {
		user_id,
		articleId,
		content,
		comment_id = '',
		reply_id = '',
		is_reply = false
	} = event
	
	// 获取文章
	const article = await db.collection('article').doc(articleId).get()
	// 获取文章的评论
	const comments = article.data[0].comments

	let user = await db.collection('user').doc(user_id).get()
	user = user.data[0]

	let comment = {
		comment_id: genID(5),
		comment_content: content,
		create_time: new Date().getTime(),
		is_reply : is_reply,
		author: {
			author_id: user._id,
			author_name: user.author_name,
			avator: user.avatar,
			professional: user.professional
		},
		replys: []
	}
	
	// 评论文章
	if(comment_id === ''){
		comment.replys = []
		comment = cmd.unshift(comment)
	} else{
		// 对回复进行评论
		// 获取评论索引
		let index = comments.findIndex(item=>item.comment_id === comment_id)
		console.log('index',index);
		let toUser = ''
		if(is_reply){
			//子回复
			toUser = comments[index].replys.find(item=>item.comment_id === reply_id)
		} else{
			// 获取回复的作者信息
			toUser = comments.find(item=>item.comment_id === comment_id)
		}
		toUser = toUser.author.author_name
		comment.to = toUser
		
		// 更新评论的回复信息
		comment = {
			[index] : {
				replys:cmd.unshift(comment)
			}
		}
		
		// 更新对象中的数组属性中某一个索引的值
		/**
			let obj = {
				arr:[{name:1},{name:2}]
			}
			
			xxx.update({
				arr : {
					1 : {
						name:3
					}
				}
			})
		 */
		
	}

	await db.collection('article').doc(articleId).update({
		comments: comment
	})
	
	//返回数据给客户端
	return {
		code: 200,
		msg: '请求成功'
	}
};

function genID(length) {
	return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
}
